<?php

/**
 * Created by PhpStorm.
 * User: zhaozhichao
 * Date: 2018/6/8
 * Time: 下午12:41
 */


define('IN_AJAX', TRUE);


if (!defined('IN_ANWSION')) {
    die;
}

class goods_ajax extends AWS_ADMIN_CONTROLLER
{
    public function setup()
    {
        HTTP::no_cache_header();
    }


    public function save_goods_action()
    {
        /**
         * 我是更新操作
         *
         */
        if (intval($_POST['goods_id'])) {

            $_POST['goods_name'] = trim($_POST['goods_name']);
            $_POST['goods_sn'] = trim($_POST['goods_sn']);
            $_POST['keywords'] = trim($_POST['keywords']);

            $_POST['cat_id'] = intval($_POST['cat_id']);

            if (!$_POST['goods_name']) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('请输入商品名')));
            }

            if (!$goods_info = $this->model('goods')->get_goods_info_by_gid($_POST['goods_id'])) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('商品不存在')));
            }


            $update_data['cat_id'] = $_POST['cat_id'];
            $update_data['goods_name'] = htmlspecialchars($_POST['goods_name']);
            $update_data['goods_sn'] = htmlspecialchars($_POST['goods_sn']);
            $update_data['keywords'] = htmlspecialchars($_POST['keywords']);
            $update_data['goods_brief'] = htmlspecialchars($_POST['goods_brief']);
            $update_data['goods_desc'] = $_POST['goods_desc'];
            $update_data['market_price'] = intval($_POST['market_price']);
            $update_data['shop_price'] = intval($_POST['shop_price']);
            $update_data['promote_price'] = intval($_POST['promote_price']);
            $update_data['give_integral'] = intval($_POST['give_integral']);
            $update_data['sort_order'] = intval($_POST['sort_order']);
            $update_data['is_on_sale'] = intval($_POST['is_on_sale']);
            $update_data['is_delete'] = intval($_POST['is_delete']);
            $update_data['is_new'] = intval($_POST['is_new']);
            $update_data['is_best'] = intval($_POST['is_best']);
            $update_data['is_hot'] = intval($_POST['is_hot']);
            $update_data['is_promote'] = intval($_POST['is_promote']);
            $update_data['has_attach'] = htmlspecialchars($_POST['has_attach']);
            $update_data['jd_url'] = htmlspecialchars($_POST['jd_url']);
            $update_data['tb_url'] = htmlspecialchars($_POST['tb_url']);

            $this->model('goods')->update_goods_fields($update_data, $goods_info['goods_id']);


            //处理图片
            if ($_POST['attach_access_key']) {
                $this->model('publish')->update_attach('goods', $goods_info['goods_id'], $_POST['attach_access_key']);
            }

            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('更新成功')));


        } else {

            /**
             * 1.插入基础商品信息
             *
             */

            $_POST['goods_name'] = trim($_POST['goods_name']);

            $_POST['goods_sn'] = trim($_POST['goods_sn']);

            $_POST['keywords'] = trim($_POST['keywords']);

            $_POST['cat_id'] = intval($_POST['cat_id']);

            if (!$_POST['goods_name']) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('请输入商品名')));
            }

            if ($this->model('goods')->check_goodsname($_POST['goods_name'])) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('商品名已经存在')));
            }

            if ($this->model('goods')->check_goodssn($_POST['goods_name'])) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('商品编码已经被使用, 或格式不正确')));
            }

            $goods_id = $this->model('goods')->insert_goods($_POST['cat_id'], $_POST['goods_name'],
                $_POST['goods_sn'],
                $_POST['keywords'],
                $_POST['is_new'],
                $_POST['is_best'],
                $_POST['is_hot'],
                $_POST['is_promote']
            );

//            $this->model('active')->set_user_email_valid_by_uid($uid);
//
//            $this->model('active')->active_user_by_uid($uid);
//
//            if ($_POST['group_id'] == 1 AND !$this->user_info['permission']['is_administortar'])
//            {
//                $_POST['group_id'] = 4;
//            }
//
//            if ($_POST['group_id'] != 4)
//            {
//                $this->model('account')->update('users', array(
//                    'group_id' => $_POST['group_id'],
//                ), 'uid = ' . $uid);
//            }

            H::ajax_json_output(AWS_APP::RSM(array(
                'url' => get_js_url('/admin/goods/goods_list/')
            ), 1, null));
        }

    }

    /**
     * 设为首图
     */
    public function save_cover_goods_action()
    {
        if ($_POST['goods_id']) {


            if (!$goods_info = $this->model('goods')->get_goods_info_by_gid($_POST['goods_id'])) {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('商品不存在')));
            }

            $update_data['cover']=htmlspecialchars($_POST['file_location']);
            $this->model('goods')->update_goods_fields($update_data, $goods_info['goods_id']);
            H::ajax_json_output(AWS_APP::RSM(null, 1, AWS_APP::lang()->_t('更新成功')));

        }else{
            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('错误的操作')));

        }
    }

    /**
     * 上传图片
     */
    public function upload_action()
    {


        if (!$goods_info = $this->model('goods')->get_goods_info_by_gid($_GET['goods_id'])) {
            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('商品不存在')));
        }
        $item_type = 'goods';

        $goods_info['gid'] = $_GET['goods_id'];

        AWS_APP::upload()->initialize(array(
            'allowed_types' => get_setting('allowed_upload_types'),
            'upload_path' => get_setting('upload_dir') . '/goods/' . $this->model('goods')->get_goods_cover($goods_info['gid'], '', 1),
            'is_image' => true,
            'max_size' => get_setting('upload_size_limit')*5
        ));

        if (isset($_GET['aws_upload_file'])) {
            AWS_APP::upload()->do_upload($_GET['aws_upload_file'], file_get_contents('php://input'));
        } else if (isset($_FILES['aws_upload_file'])) {
            AWS_APP::upload()->do_upload('aws_upload_file');
        } else {
            return false;
        }

        if (AWS_APP::upload()->get_error()) {
            switch (AWS_APP::upload()->get_error()) {
                default:
                    die("{'error':'错误代码: " . AWS_APP::upload()->get_error() . "'}");
                    break;

                case 'upload_invalid_filetype':
                    die("{'error':'文件类型无效'}");
                    break;

                case 'upload_invalid_filesize':
                    die("{'error':'文件尺寸过大, 最大允许尺寸为 " . get_setting('upload_size_limit')*5 . " KB'}");
                    break;
            }
        }

        if (!$upload_data = AWS_APP::upload()->data()) {
            die("{'error':'上传失败, 请与管理员联系'}");
        }

        if ($upload_data['is_image'] == 1) {
            foreach (AWS_APP::config()->get('image')->goods_thumbnail AS $key => $val) {
                $thumb_file[$key] = $upload_data['file_path'] . $val['w'] . 'x' . $val['h'] . '_' . basename($upload_data['full_path']);

                AWS_APP::image()->initialize(array(
                    'quality' => 90,
                    'source_image' => $upload_data['full_path'],
                    'new_image' => $thumb_file[$key],
                    'width' => $val['w'],
                    'height' => $val['h']
                ))->resize();
            }
        }

        $attach_id = $this->model('goods')->add_cover($goods_info['gid'], $item_type, $upload_data['orig_name'], $_GET['attach_access_key'], time(), basename($upload_data['full_path']), $upload_data['is_image']);

        $output = array(
            'success' => true,
            'delete_url' => get_js_url('/publish/ajax/remove_attach/attach_id-' . AWS_APP::crypt()->encode(json_encode(array(
                    'attach_id' => $attach_id,
                    'access_key' => $_GET['attach_access_key']
                )))),
            'attach_id' => $attach_id,
            'attach_tag' => 'attach'

        );

        $attach_info = $this->model('goods')->get_cover_by_id($attach_id);

        if ($attach_info['thumb']) {
            $output['thumb'] = $attach_info['thumb'];
        } else {
            $output['class_name'] = $this->model('publish')->get_file_class(basename($upload_data['full_path']));
        }

        exit(htmlspecialchars(json_encode($output), ENT_NOQUOTES));
    }

    /**
     * 获取商品相册
     */
    public function goods_attach_edit_list_action()
    {
//        if (! $question_info = $this->model('goods')->get_question_info_by_id($_POST['goods_id']))
//        {
//            H::ajax_json_output(AWS_APP::RSM(null, '-1', AWS_APP::lang()->_t('无法获取附件列表')));
//        }

//        if ($question_info['published_uid'] != $this->user_id AND !$this->user_info['permission']['is_administortar'] AND !$this->user_info['permission']['is_moderator'])
//        {
//            H::ajax_json_output(AWS_APP::RSM(null, '-1', AWS_APP::lang()->_t('你没有权限编辑这个附件列表')));
//        }

        if ($question_attach = $this->model('goods')->get_cover('goods', $_POST['goods_id'])) {
            foreach ($question_attach as $attach_id => $val) {
                $question_attach[$attach_id]['class_name'] = $this->model('publish')->get_file_class($val['file_name']);

                $question_attach[$attach_id]['delete_link'] = get_js_url('/publish/ajax/remove_attach/attach_id-' . AWS_APP::crypt()->encode(json_encode(array(
                        'attach_id' => $attach_id,
                        'access_key' => $val['access_key']
                    ))));

                $question_attach[$attach_id]['attach_id'] = $attach_id;
                $question_attach[$attach_id]['attach_tag'] = 'attach';
            }
        }

        H::ajax_json_output(AWS_APP::RSM(array(
            'attachs' => $question_attach
        ), 1, null));
    }


    /**
     *
     * 商品规格
     */
    public  function save_goods_style_action()
    {
        if (!$goods = $this->model('goods')->get_goods_info_by_gid($_POST['goods_id'])){
            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('没有商品信息')));

        }


        if ($_FILES['goods_color_pic']['name'])
        {
            AWS_APP::upload()->initialize(array(
                'allowed_types' => 'jpg,jpeg,png,gif',
                'upload_path' => get_setting('upload_dir') . '/goods/' . $this->model('goods')->get_goods_cover($goods['goods_id'], '', 1),
                'is_image' => TRUE,
                'max_size' => get_setting('upload_size_limit')*5
            ))->do_upload('goods_color_pic');

            if (AWS_APP::upload()->get_error())
            {
                switch (AWS_APP::upload()->get_error())
                {
                    default:
                        H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('错误代码') . ': ' . AWS_APP::upload()->get_error()));
                        break;

                    case 'upload_invalid_filetype':
                        H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('文件类型无效')));
                        break;

                    case 'upload_invalid_filesize':
                        H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('文件尺寸过大, 最大允许尺寸为 %s KB', get_setting('upload_size_limit')*5 )));
                        break;
                }
            }

            if (! $upload_data = AWS_APP::upload()->data())
            {
                H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('上传失败, 请与管理员联系')));
            }

            if ($upload_data['is_image'] == 1)
            {
                foreach(AWS_APP::config()->get('image')->goods_thumbnail AS $key => $val)
                {
//                    $thumb_file[$key] = $upload_data['file_path'] . $this->model('goods')->get_goods_cover($goods['goods_id'], $key, 2);
                    $thumb_file[$key] = $upload_data['file_path'] . $val['w'] . 'x' . $val['h'] . '_' . basename($upload_data['full_path']);

                    AWS_APP::image()->initialize(array(
                        'quality' => 90,
                        'source_image' => $upload_data['full_path'],
                        'new_image' => $thumb_file[$key],
                        'width' => $val['w'],
                        'height' => $val['h']
                    ))->resize();
                }
            }
//            var_dump($upload_data);
            $update_data['goods_color_pic'] = $upload_data['file_name'];//$this->model('goods')->get_avatar($user_info['uid'], null, 1) . basename($thumb_file['min']);
        }


        $update_data['gid'] = $goods['goods_id'];
        $update_data['goods_color'] = htmlspecialchars($_POST['goods_color']);
        $update_data['goods_color_name'] = trim($_POST['goods_color_name']);
//            $update_data['goods_color_pic'] = ;
        $update_data['goods_model'] = htmlspecialchars($_POST['goods_model']);
        $update_data['goods_total'] = intval($_POST['goods_total']);

        //更新
        if(intval($_POST['style_id'])){

            $this->model('goods')->update_goods_style_fields($update_data, $_POST['style_id']);


        }else{

//            创建
            $this->model('goods')->insert_goods_style_fields($update_data);


        }
        H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('操作成功')));




    }

    /**
     * 专题
     */

    public  function  save_goods_special_action(){

        $update_data['title'] =  trim($_POST['title']);
        $update_data['banner'] =  trim($_POST['banner']);
        $update_data['video'] =  trim($_POST['video']);
        $update_data['container'] =  jsonp_encode($_POST['container']);
        $update_data['state'] =  $_POST['state'];
//        var_dump($_POST['container']);


        $result = $this->model('goodsSpecial')->update_goods_special_fields($update_data, intval($_POST['id']));

        if($result){
            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('操作成功')));

        }else{
            H::ajax_json_output(AWS_APP::RSM(null, -1, AWS_APP::lang()->_t('失败')));

        }


    }

}
